/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lanchat.model.net;

import com.lanchat.model.util.LocalIPGetter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 广播信息的接收类，此类设置为线程，保持接收状态
 * 
 * @author zhangzhe
 */
public class BroadcastReceiver implements Runnable {

    private InetAddress group;
    private MulticastSocket socket;
    private DatagramPacket packet;
    private Thread thread;

    public BroadcastReceiver() {
        BroadcastAddr info= new BroadcastAddr();
        info.setNetaddr(LocalIPGetter.getMyIP());
        info.setNetmask("255.255.0.0");
        info.execCalc();
        try {
            group = InetAddress.getByName(info.getNetbroadcastaddr());
            socket=new MulticastSocket(NetConstant.BROADCAST_PORT);
            socket.setTimeToLive(NetConstant.BROADCAST_TIMETOLIVE);
            socket.joinGroup(group);
        } catch (IOException ex) {
            Logger.getLogger(BroadcastReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        
    }
    public Object Recv(){
        Object obj=new Object();
        byte[] buffer=new byte[NetConstant.DATAGRAMPACKET_SIZE];
        DatagramPacket dp=new DatagramPacket(buffer, buffer.length);
        if(!socket.isClosed()){
            try {
                ObjectInputStream in = null;
                socket.receive(dp);
                byte[] data =new byte[dp.getLength()];
                System.arraycopy(dp.getData(), dp.getOffset(), data, 0, data.length);
                in=new ObjectInputStream(new ByteArrayInputStream(data));
                try {
                    obj = in.readObject();
                    in.close();
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(BroadcastReceiver.class.getName()).log(Level.SEVERE, null, ex);
                    in.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(BroadcastReceiver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return obj;
    }
}
